package com.kkw.shoppingmall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kkw.common.constant.OrderConstant;
import com.kkw.common.exception.NoStockException;
import com.kkw.common.to.mq.OrderTo;
import com.kkw.common.to.mq.SeckillOrderTo;
import com.kkw.common.utils.R;
import com.kkw.common.vo.MemberResVo;
import com.kkw.shoppingmall.order.entity.OrderItemEntity;
import com.kkw.shoppingmall.order.entity.PaymentInfoEntity;
import com.kkw.shoppingmall.order.enume.OrderStatusEnum;
import com.kkw.shoppingmall.order.feign.CartFeignService;
import com.kkw.shoppingmall.order.feign.MemberFeignService;
import com.kkw.shoppingmall.order.feign.ProductFeignService;
import com.kkw.shoppingmall.order.feign.WareFeignService;
import com.kkw.shoppingmall.order.interceptor.LoginUserInterceptor;
import com.kkw.shoppingmall.order.service.OrderItemService;
import com.kkw.shoppingmall.order.service.PaymentInfoService;
import com.kkw.shoppingmall.order.vo.*;
//import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkw.common.utils.PageUtils;
import com.kkw.common.utils.Query;

import com.kkw.shoppingmall.order.dao.OrderDao;
import com.kkw.shoppingmall.order.entity.OrderEntity;
import com.kkw.shoppingmall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    //ThreadLocal使用完后一定要释放 否则多了就会内存溢出  confirmVoThreadLocal.set(null);
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注意在异步模式下 fegin会丢失上下文，和fegin丢失请求头不是一个问题了
     * RequestContextHolder.getRequestAttributes 即丢失这个
     * 下单前还要确认订单
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        //解决异步任务时 fegin丢失上下文的情况
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        OrderConfirmVo confirmVo = new OrderConfirmVo();
        MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
        CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            //每一个任务都共享一下请求的上下文    即每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //1、远程查询所有的收获地址
            List<MemberAddressVo> address = memberFeignService.getAddress(memberResVo.getId());
            confirmVo.setAddress(address);
        }, executor);


        //2、远程调用购物车  为什么会出现问题 认为没有登录
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            //每一个任务都共享一下请求的上下文  即每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //feign在远程调用之前要构造请求，调用很多的拦截器（因为它自己构造了 所以会丢失请求头）
            List<OrderItemVo> items = cartFeignService.currentUserItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hashStock = wareFeignService.getSkuHasStock(collect);
            List<SkuStockVo> data = hashStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }

        });

        //只有这两个任务都完成了 才不会阻塞下面
        //3、查询用户积分
        Integer integration = memberResVo.getIntegration();
        confirmVo.setIntegration(integration);
        //4、其他数据自动计算

        //todo 5、防重令牌 防止重复下单 保证订单的幂等性 存放在redis里面然后再  支付的时候再次去使用redis的 setnx
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();


        return confirmVo;
    }

    /**
     * 提交了订单，成功则去支付页面
     *  @GlobalTransactional seata分布式事务的注解   高并发模式下不适合使用
     * @param vo
     * @return
     */
//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        try {
            confirmVoThreadLocal.set(vo);
            //验证令牌[令牌的对比和删除必须保证原子性] 假设他在页面很快的重复点2次 redis里面也是会有他的数据多条  所以就要保证原子性
            //所以用脚本来保证原子性  或者用redisson也可以
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            MemberResVo memberResVo = LoginUserInterceptor.loginUser.get();
            String orderToken = vo.getOrderToken();
            //原子验证令牌和删除令牌   如果这个令牌不存在则直接返回0 如果令牌存在则 返回 （令牌失败0      删除成功1）  因为这个令牌是前端带来的 要保证原子性操作就必须使用到lua脚本
            Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId()), orderToken);
            if (result == 0L) {
                //令牌验证失败
                response.setCode(1);
                return response;
            } else {
                //令牌验证成功
                //1、创建订单，订单项等信息
                OrderCreatTo order = cretaOrder();
                //2、验价
                //后台算的金额
                BigDecimal payAmount = order.getOrder().getPayAmount();
                //前端穿回来的金额
                BigDecimal payPrice = vo.getPayPrice();
                if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
                    //金额对比   差值小于0.01就是可接收的范围

                    //3、保存订单
                    saveOrder(order);
                    //4、锁库存。只要有异常 回滚订单数据
                    WareSkuLockVo lockVo = new WareSkuLockVo();
                    lockVo.setOrderSn(order.getOrder().getOrderSn());
                    List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                        OrderItemVo itemVo = new OrderItemVo();
                        itemVo.setSkuId(item.getSkuId());
                        itemVo.setCount(item.getSkuQuantity());
                        itemVo.setTitle(item.getSkuName());
                        return itemVo;
                    }).collect(Collectors.toList());
                    lockVo.setLocks(locks);
                    // 远程锁库存
                    //为了保证高并发  库存服务自己回滚
                    //1）可以发消息给库存服务自己回滚
                    //2）库存服务本身也可以使用自动解锁模式  （使用消息队列）
                    R r = wareFeignService.orderLockStock(lockVo);
                    if (r.getCode() == 0) {
                        //锁成功
                        response.setOrder(order.getOrder());

                        //todo 5、远程扣减积分
                        //模拟订单创建失败，进行库存等回滚
    //                    int i=10/0;
                        //todo 订单创建成功发送消息给mq
                        rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                        log.info("发送消息给mq成功:{}",order.getOrder().toString());
                        response.setCode(0);
                        return response;
                    } else {
                        //锁失败
                        response.setCode(3);
                        return response;
                    }

                } else {
                    //金额对比失败
                    response.setCode(2);
                    return response;
                }
            }
        } catch (AmqpException e) {
            System.out.println("错误的信息"+e.getMessage());
        }

        //不这样写了 用lua脚本来实现原子性操作
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId());
//        if (redisToken != null &&orderToken.equals(redisToken)) {
//            //令牌验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberResVo.getId());
//        }else {
//            //不通过
//            return null;
//        }
        return  response;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public void closeOrder(OrderEntity entity) {
        //查询当前订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        //关单
        if (orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
        }
        //发给mq一个信息 主动去让mq去释放库存
        OrderTo orderTo = new OrderTo();
        BeanUtils.copyProperties(orderEntity,orderTo);
        try {
            //todo 保证消息一定会发出去 即可靠生产
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        } catch (AmqpException e) {
            e.printStackTrace();
            //todo 将没法发送成功的消息重新发送
            //1）可以用while循环发送
            //2）每一个消息都可以做好日志记录 然后使用定时任务（给数据库保存每一个消息的详细信息 （创建一张表记录 rout_key content发送的内容等等））
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        //即设置  显示小数点两位  11.0000->11.00   向上取值
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        //设置主题
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItemEntity = order_sn.get(0);
        payVo.setSubject(orderItemEntity.getSkuName());
        payVo.setBody(orderItemEntity.getSkuAttrsVals());

        return payVo;
    }

    /**
     * 查询当前用户所有订单数据
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

        MemberResVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id",memberResponseVo.getId()).orderByDesc("create_time")
        );

        //遍历所有订单集合
        List<OrderEntity> orderEntityList = page.getRecords().stream().map(order -> {
            //根据订单号查询订单项里的数据
            List<OrderItemEntity> orderItemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>()
                    .eq("order_sn", order.getOrderSn()));
            order.setItemEntities(orderItemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(orderEntityList);
        if (orderEntityList.size()<=0){
            ArrayList<OrderEntity> orderEntities = new ArrayList<>();
            page.setRecords(orderEntities);
        }


        return new PageUtils(page);
    }

    /**
     * 处理支付宝返回的数据
     * <p>
     * 只要我们收到了，支付宝给我们的一步的通知，告诉我订单支付成功
     * 返回success，支付宝就再也不通知
     */
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {

        //1.保存交易流水这个对象 PaymentInfoEntity
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());//修改数据库为唯一属性
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(paymentInfoEntity);

        log.info("保存流水号："+payAsyncVo.getOut_trade_no());
        //2。修改订单状态
        if (payAsyncVo.getTrade_status().equals("TRADE_SUCCESS") || payAsyncVo.getTrade_status().equals("TRADE_FINISHED")) {
            //支付成功
            String outTradeNo = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(outTradeNo, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //todo 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal payAmount = seckillOrderTo.getSeckillPrice().multiply(new BigDecimal("" + seckillOrderTo.getNum()));
        orderEntity.setPayAmount(payAmount);
        this.save(orderEntity);
        //todo保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderItemEntity.setRealAmount(payAmount);
//       todo 获取当前sku的详细信息进行设置 productFeignService.getSpuInfoBySkuId();
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());

        orderItemService.save(orderItemEntity);


    }

    /**
     * 保存订单
     *
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreatTo orderCreateTo) {

        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        this.save(order);
//        this.baseMapper.insert(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        //批量保存订单项数据
        orderItemService.saveBatch(orderItems);

    }

    private OrderCreatTo cretaOrder() {
        OrderCreatTo createTo = new OrderCreatTo();
        //1、生成订单号
        String orderSn = IdWorker.getTimeId();
        //创建订单
        OrderEntity orderEntity = buildOrder(orderSn);

        //2、获取到所有的订单项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        //3、计算价格、积分相关
        computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);
        createTo.setOrderItems(itemEntities);

        return createTo;
    }

    /**
     * 计算价格的方法
     *
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);
        //设置订单的相关状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());


        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }


    private OrderEntity buildOrder(String orderSn) {
        MemberResVo respVo = LoginUserInterceptor.loginUser.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());
        //获取收获地址的信息
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();

        R fare = wareFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });
        //设置运费金额
        entity.setFreightAmount(fareResp.getFare());
        //设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }

    /**
     * 构建所有订单项数据
     *
     * @param
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        //为什么不用传参数  因为购物车服务里面已经有对应的用户cookie信息在fegin请求头里面了
        List<OrderItemVo> currentUserItems = cartFeignService.currentUserItems();
        if (currentUserItems != null && currentUserItems.size() > 0) {
            List<OrderItemEntity> itemEntites = currentUserItems.stream().map(carItem -> {
                OrderItemEntity itemEntity = buildOrderItem(carItem);
                ;
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntites;
        }
        return null;
    }

    /**
     * 构建某一个订单项
     *
     * @param
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo items) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandId().toString());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttr(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}